<?php

namespace app\api\controller\common;

use think\Controller;
use app\api\model\Role as RoleModel;
use app\api\model\Admin as AdminModel;
use app\api\model\Auth as AuthModel;
use app\api\model\Media;
use app\api\model\MediaFiles;

/**
 * 接口控制器基类
 * 会走权限验证，除了common/index控制器，其余控制器都需继承此类
 */
class ApiBase extends Controller
{

    public function __construct()
    {
        parent::__construct();
        if (!$this->isLogin()) {
            echo json_encode(array('code' => '-1', 'msg' => '请先登录！'));
            die;
        }
        //校验权限
        if(!$this->hasAuth()){
            echo json_encode(array('code' => '0', 'msg' => '您没有权限'));die;
        }

    }

    /**
     * 校验是否登录
     *
     * @return void
     */
    private function isLogin()
    {
        // code 1 成功,0失败,-1未登录或登录过期
        if (!session('?admin')) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 校验是否有操作权限
     *
     * @return void
     */
    public function hasAuth()
    {
        $controller = strtolower(request()->controller());
        $controllerArr = explode('.', $controller);
        $action = request()->action();
        //获取用户的权限集合
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        if ($admin['is_super'] != 1) {
            $authArr = $this->getAuthList($admin['id']);
            // halt($authArr);
            $permArr = [
                // 'm' => false, //模块是否有权限（这里的模块是指控制器所在文件夹名，比如控制器admin.php所在文件夹名为permission）
                // 'c' => false, //控制器是否有权限
                'a' => false, //方法是否有权限
            ];
            foreach ($authArr as $v) {
                // if ($v['rule'] === $controllerArr[0]) {
                //     $permArr['m'] = true;
                // }
                // if ($v['rule'] === $controllerArr[0] . ',' . $controllerArr[1]) {
                //     $permArr['c'] = true;
                // }
                if ($v['rule'] === $controllerArr[0] . ',' . $controllerArr[1] . ',' . $action) {
                    $permArr['a'] = true;
                }
            }

            // if (!($permArr['m'] && $permArr['c'] && $permArr['a'])) {
            //     return false;
            // }
            if (!$permArr['a']) {
                return false;
            }
        }
        $auth1 = AuthModel::where(['rule' => $controllerArr[0]])->field('auth_name,status,rule')->find();
        //校验模块是否开启
        if ($auth1['status']==0) {
            return false;
        }
        $auth2 = AuthModel::where(['rule' => $controllerArr[0] . ',' . $controllerArr[1]])->field('auth_name,status,rule')->find();
        //校验控制器是否开启
        if ($auth2['status']==0) {
            return false;
        }
        $auth3 = AuthModel::where(['rule' => $controllerArr[0] . ',' . $controllerArr[1] . ',' . $action])->field('auth_name,status,rule')->find();
        //校验方法是否开启
        if ($auth3['status']==0) {
            return false;
        }
        $content = !empty($auth1['auth_name']) ? $auth1['auth_name'] : '';
        $content .= !empty($auth2['auth_name']) ? '/' . $auth2['auth_name'] : '';
        $content .= !empty($auth3['auth_name']) ? '/' . $auth3['auth_name'] : '';

//        var_dump($post['page']);die();
        if (!empty($content)) {
            $keyword='';
            if(!empty($auth3['rule'])){
                $keyword=$this->getKeyWord($auth3['rule']);
            }
            write_admin_log($content,$keyword,$auth1['rule'],$auth2['rule'],$auth3['rule']);
        }
        return true;
    }


    public function getKeyWord($role){
        $post = input('post.');
        $content='';
        $Medias=new Media();
        $MediaFiles=new MediaFiles();
        // 检索列表
        if($role == 'homepage,media,list' || $role == 'homepage,upload,list'){
            if(!empty($post['title'])){
                $content.='关键词:'.$post['title'].',';
            }
            if(array_key_exists("type", $post)){
                $content.='资源类型：'.($post['type']==0?'图片':($post['type']==1?'视频':'全部')).',';
            }
            if(array_key_exists("shooting_time_sort", $post)){
                $content.='拍摄时间排序：'.($post['shooting_time_sort']=='desc'?'降序':($post['shooting_time_sort']=='asc'?'升序':'全部')).',';
            }
            if(array_key_exists("download_num_sort", $post)){
                $content.='下载次数排序：'.($post['download_num_sort']=='desc'?'降序':($post['download_num_sort']=='asc'?'升序':'全部')).',';
            }
        }
        // 媒资编辑、新增
        if($role == 'homepage,upload,edit' || $role == 'homepage,upload,add'){
            if(array_key_exists("media_id", $post) && !empty($post['media_id'])){
                $detail = $Medias->getMediaData($post['media_id']);
                $title=array_key_exists("title", $post)?$post['title']:'';
                $shooting_time=array_key_exists("shooting_time", $post)?$post['shooting_time']:'';
                $cate_ids=array_key_exists("cate_ids", $post)?$post['cate_ids']:'';
                $contents=array_key_exists("content", $post)?$post['content']:'';
                if (!empty($detail)) {
                    if($title && $title!=$detail['title']){
                        $content.='更新名称：原'.$detail['title'].',更新为：'.$post['title'].',';
                    }
                    if($shooting_time && $shooting_time!=$detail['shooting_time']){
                        $content.='更新上传日期：原'.$detail['shooting_time'].',更新为：'.$post['shooting_time'].',';
                    }
                    if($cate_ids && $cate_ids!=$detail['cate_ids']){
                        $content.='更新标签：原'.$detail['cate_ids'].',更新为：'.$post['cate_ids'].',';
                    }
                    if($contents && $contents!=$detail['content']){
                        $content.='更新详情：原'.$detail['content'].',更新为：'.$post['content'].',';
                    }
                }
            }else{
                if(array_key_exists("title", $post)){
                    $content.='新增内容：'.$post['title'];
                }
            }
        }
        // 详情
        if($role == 'homepage,media,detail'){
            if(array_key_exists("media_id", $post)){
                $detail = $Medias->getMediaData($post['media_id']);
                if (!empty($detail)) {
                    $content.='查看：'.$detail['title'];
                }
            }
        }
        //单个下载
        if($role == 'homepage,media,download_file'){
            if(array_key_exists("media_file_id", $post)){
                $detail = $MediaFiles->get($post['media_file_id']);
                if (!empty($detail)) {
                    $content.='下载：'.$detail['title'];
                }
            }
        }
        //打包下载
        if($role == 'homepage,media,download_media'){
            if(array_key_exists("media_id", $post)){
                $detail = $Medias->get($post['media_id']);
                if (!empty($detail)) {
                    $content.='打包下载：'.$detail['title'];
                }
            }
        }

        //列表删除
        if($role == 'homepage,upload,del'){
            if(array_key_exists("detail", $post)){
                $content.='媒资目录删除：'.$post['detail'];
            }
        }

        //资源删除
        if($role == 'homepage,upload,media_file_del'){
            if(array_key_exists("detail", $post)){
                $content.='资源删除：'.$post['detail'];
            }
        }

        //类目
        if($role == 'tagmanage,main,add'){
            if(array_key_exists("title", $post)){
                $content.='新增标签：'.$post['title'];
            }
        }

        if($role == 'tagmanage,main,edit'){
            if(array_key_exists("title", $post)){
                $content.='编辑标签：'.$post['title'];
            }
        }

        if($role == 'tagmanage,main,del'){
            if(array_key_exists("detail", $post)){
                $content.='删除标签：'.$post['detail'];
            }
        }
        if($role == 'tagmanage,main,edit_disabled' || $role == 'tagmanage,main,edit_warn'){
            if(array_key_exists("detail", $post)){
                $content.=$post['detail'];
            }
        }

        //用户
        if($role == 'permission,admin,add'){
            if(array_key_exists("account", $post)){
                $content.='新增管理员：账号：'.$post['account'].'用户名'.$post['realname'];
            }
        }

        if($role == 'permission,admin,edit'){
            if(array_key_exists("account", $post)){
                $content.='编辑管理员：账号：'.$post['account'].',用户名'.$post['realname'].',账号id'.$post['id'];
            }
        }
        if($role == 'permission,admin,del'){
            if(array_key_exists("id", $post)){
                $content.='删除管理员：'.'账号id'.$post['id'];
            }
        }

        if($role == 'permission,admin,delorg' || $role == 'permission,admin,batchdel'){
            if(array_key_exists("ids", $post)){
                $content.='删除组：'.'组id'.$post['ids'];
            }
            if(array_key_exists("id", $post)){
                $content.='删除组：'.'组id'.$post['id'];
            }
        }

        if($role == 'permission,admin,addorg'){
            if(array_key_exists("org_name", $post)){
                $content.='新增组：'.$post['org_name'];
            }
        }

        if($role == 'permission,admin,editorg'){
            if(array_key_exists("org_name", $post)){
                $content.='编辑组：'.$post['org_name'];
            }
        }

        if($role == 'permission,role,add'){
            if(array_key_exists("role_name", $post)){
                $content.='新建角色：'.$post['role_name'];
            }
        }

        if($role == 'permission,role,edit'){
            if(array_key_exists("role_name", $post)){
                $content.='编辑角色：'.$post['role_name'];
            }
        }

        if($role == 'permission,role,del'){
            if(array_key_exists("id", $post)){
                $content.='删除组：'.'角色id'.$post['id'];
            }
        }

        return $content?$content:'查看';

    }

    /**
     * 获取用户的权限集合
     *
     * @param int $adminId
     * @return array
     */
    private function getAuthList($adminId)
    {
        $admin = AdminModel::get(['id' => $adminId]);
        $roleIds = [];
        $arr = collection($admin->role)->toArray();
        foreach ($arr as $v) {
            if ($v['status'] == 1) {
                array_push($roleIds, $v['id']);
            }
        }
        $roleIdsStr = implode(',', $roleIds);
        $role = RoleModel::all(['id' => ['in', $roleIdsStr], 'status' => 1], 'auth');
        $roleArr = collection($role)->toArray();
        $authArr = [];
        foreach ($roleArr as $v) {
            foreach ($v['auth'] as $vv) {
                $d = $vv;
                unset($d['create_time'], $d['update_time']);
                if ($vv['status'] == 1) {
                    array_push($authArr, $d);
                }
            }
        }
        return $authArr;
    }

    public function returnJson($code = 0, $msg = '', $data = [])
    {
        header('Content-type: application/json');
        echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
        exit();
    }
}
